<?php
namespace app\models;

use laiq\base\Model;
use laiq\db\Connection;

/**
 * 标签Model
 */
class TagModel extends Model
{
    protected $table = 'tag';

    /**
     * 获取所有标签
     *
     * @param integer $limit 0=获取所有
     * @param integer $offset
     * @return void
     */    
    public function findTags($limit=20, $offset=0, $key='') {
        if ($offset) {
            $this->where('id', $offset, '>');
        }
        if ($limit) {
            $this->limit($limit);
        }
        $rows = $this->findAll();
        // 结果以key作为键值  
        if ($key && $rows && isset(current($rows)[$key])) {
            $fRows = [];      
            foreach ($rows as $row) {
                $sKey = $row[$key];
                $fRows[$sKey] = $row; 
            }
            $rows = $fRows;
            unset($fRows);
        } 
        return $rows; 
    }

    public function addTag($name) {
        if (!$name) {
            throw new \Exception('Miss Param');
        }
        $this->where('name', $name, '=');
        $row = $this->findOne();
        if ($row) {
            throw new \Exception("{$name}已存在");
        }
        $sql = "INSERT INTO `{$this->table}`(`name`) values('$name')";
        return $this->exec($sql);
    }
}